package com.itee.core.serial;

import com.itee.core.util.StringCoder;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

/**
 * Created by xin on 2014/4/21 0021.
 */
public abstract class SerialSession {

    protected IoSession session;

    /**
     * 收到报文进行处理
     *
     * @param messages
     */
    public abstract void messageReceived(Object messages);

    /**
     * 对报文进行初步处理
     *
     * @param session
     * @param buff
     * @param out
     * @return
     * @throws Exception
     */
    public abstract boolean doDecode(IoSession session, IoBuffer buff, ProtocolDecoderOutput out) throws Exception;

    public abstract String getName();

    public SerialSession(IoSession session) {
        session.setAttribute(SerialHandler.NAME, getName());
        this.session = session;
    }

    public void sendPacket(byte[] datas) {
        session.write(IoBuffer.wrap(datas));
        String s = new String(datas);
        System.out.println(" >> " + s);
    }
    
    public void close() {
        this.session.close(true);
    }

    public boolean isConnected() {
        return session.isConnected();
    }

    public boolean isClosing() {
        return session.isClosing();
    }

}
